<template>
  <div>
    <n-modal v-model:show="showModal" :mask-closable="false" :show-icon="false" preset="dialog"
      transform-origin="center" :title="formValue.id > 0 ? '编辑商品 #' + formValue.id : '添加商品'" :style="{
        width: dialogWidth,
      }">
      <n-scrollbar style="max-height: 87vh" class="pr-5">
        <n-spin :show="loading" description="请稍候...">
          <n-form ref="formRef" :model="formValue" :rules="rules"
            :label-placement="settingStore.isMobile ? 'top' : 'left'" :label-width="100" class="py-4">
            <n-grid cols="1 s:1 m:1 l:1 xl:1 2xl:1" responsive="screen">
              <n-gi span="1">
                <n-form-item label="商品标题" path="title">
                  <n-input placeholder="请输入商品标题" v-model:value="formValue.title" />
                </n-form-item>
              </n-gi>
              <n-gi span="1">
                <n-form-item label="商品子标题" path="subtitle">
                  <n-input placeholder="请输入商品子标题" v-model:value="formValue.subtitle" />
                </n-form-item>
              </n-gi>
              <n-gi span="1">
                <n-form-item label="商品编码" path="code">
                  <n-input placeholder="请输入商品编码" v-model:value="formValue.code" />
                </n-form-item>
              </n-gi>
              <n-gi span="1">
                <n-form-item label="分享文案" path="shareContent">
                  <n-input type="textarea" placeholder="分享文案" v-model:value="formValue.shareContent" />
                </n-form-item>
              </n-gi>
              <n-gi span="1">
                <n-form-item label="商品主图" path="image">
                  <UploadImage :maxNumber="1" v-model:value="formValue.image" />
                </n-form-item>
              </n-gi>
              <n-gi span="1">
                <n-form-item label="商品图片" path="images">
                  <UploadImage :maxNumber="6" v-model:value="formValue.imagesList" />
                </n-form-item>
              </n-gi>
              <n-gi span="1">
                <n-form-item label="售价（分）" path="price">
                  <n-input-number placeholder="请输入售价（分）" v-model:value="formValue.price" />
                </n-form-item>
              </n-gi>
              <n-gi span="1">
                <n-form-item label="库存" path="stock">
                  <n-input-number placeholder="请输入库存" v-model:value="formValue.stock" />
                </n-form-item>
              </n-gi>
              <n-gi span="1">
                <n-form-item label="是否限购" path="limit">
                  <n-radio-group v-model:value="formValue.limit" name="limit">
                    <n-radio-button v-for="limit in dict.getOptionUnRef('sys_normal_disable')" :key="limit.value"
                      :value="limit.value" :label="limit.label" />
                  </n-radio-group>
                </n-form-item>
              </n-gi>
              <n-gi span="1">
                <n-form-item label="虚拟销量" path="fakeSale">
                  <n-input-number placeholder="请输入虚拟销量" v-model:value="formValue.fakeSale" />
                </n-form-item>
              </n-gi>
              <n-gi span="1">
                <n-form-item label="真实销量" path="sale">
                  <n-input-number placeholder="请输入真实销量" v-model:value="formValue.sale" />
                </n-form-item>
              </n-gi>
              <n-gi span="1">
                <n-form-item label="是否热门" path="isHot">
                  <n-switch :unchecked-value="2" :checked-value="1" v-model:value="formValue.isHot" />
                </n-form-item>
              </n-gi>
              <n-gi span="1">
                <n-form-item label="上架状态" path="status">
                  <n-switch :unchecked-value="2" :checked-value="1" v-model:value="formValue.status" />
                </n-form-item>
              </n-gi>
              <n-gi span="1">
                <n-form-item label="排序" path="sort">
                  <n-input-number placeholder="请输入排序" v-model:value="formValue.sort" />
                </n-form-item>
              </n-gi>
              <n-gi span="1">
                <n-form-item label="属性" path="attrs">
                  <n-dynamic-input v-model:value="formValue.attrs" preset="pair" :on-create="handleAttrCreate">
                    <template #default="{ value }">
                      <div style="display: flex; align-items: center; width: 100%">
                        <n-input v-model:value="value.name" type="text" placeholder="名称" />
                        <n-input v-model:value="value.value" type="text" placeholder="内容" />
                      </div>
                    </template>
                  </n-dynamic-input>
                </n-form-item>
              </n-gi>
              <n-gi span="1">
                <n-form-item label="规格" path="skus">
                  <n-dynamic-input v-model:value="formValue.skus" preset="pair" :on-create="handleSkuCreate">
                    <template #default="{ value }">
                      <div style="display: flex; align-items: center; width: 100%">
                        <n-input v-model:value="value.price" type="text" placeholder="价格" />
                        <n-input v-model:value="value.name" type="text" placeholder="名称" />
                        <n-input v-model:value="value.code" type="text" placeholder="编码" />
                        <n-input v-model:value="value.stock" type="text" placeholder="库存" />
                      </div>
                    </template>
                  </n-dynamic-input>
                </n-form-item>
              </n-gi>

              <n-gi span="1">
                <n-form-item label="详情" path="content">
                  <Editor style="height: 450px" id="content" v-model:value="formValue.content" />
                </n-form-item>
              </n-gi>
            </n-grid>
          </n-form>
        </n-spin>
      </n-scrollbar>
      <template #action>
        <n-space>
          <n-button @click="closeForm">
            取消
          </n-button>
          <n-button type="info" :loading="formBtnLoading" @click="confirmForm">
            确定
          </n-button>
        </n-space>
      </template>
    </n-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed } from 'vue';
import { useDictStore } from '@/store/modules/dict';
import { Edit, View, MaxSort } from '@/api/storeProduct';
import { State, newState, rules } from './model';
import UploadImage from '@/components/Upload/uploadImage.vue';
import { useProjectSettingStore } from '@/store/modules/projectSetting';
import { useMessage } from 'naive-ui';
import { adaModalWidth } from '@/utils/hotgo';

const emit = defineEmits(['reloadTable']);
const message = useMessage();
const settingStore = useProjectSettingStore();
const dict = useDictStore();
const loading = ref(false);
const showModal = ref(false);
const formValue = ref<State>(newState(null));
const formRef = ref<any>({});
const formBtnLoading = ref(false);
const dialogWidth = computed(() => {
  return adaModalWidth(840);
});

// 提交表单
function confirmForm(e) {
  e.preventDefault();
  formRef.value.validate((errors) => {
    if (!errors) {
      formBtnLoading.value = true;
      let imagesList = formValue.value.imagesList;
      let images = ref<any>([])
      for (let i = 0; i < imagesList.length; i++) {
        images.value[i] = { image: imagesList[i] }
      }
      formValue.value.images = images.value
      Edit(formValue.value)
        .then((_res) => {
          message.success('操作成功');
          closeForm();
          emit('reloadTable');
        })
        .finally(() => {
          formBtnLoading.value = false;
        });
    } else {
      message.error('请填写完整信息');
    }
  });
}

// 关闭表单
function closeForm() {
  showModal.value = false;
  loading.value = false;
}

function handleSkuCreate(value) {
  return {
    stock: '0',
    name: '',
    code: '',
    price: ''
  };
}
function handleAttrCreate(value) {
  return {
    name: '',
    value: ''
  };
}

// 打开模态框
function openModal(state: State) {
  showModal.value = true;

  // 新增
  if (!state || state.id < 1) {
    formValue.value = newState(state);

    loading.value = true;
    MaxSort()
      .then((res) => {
        formValue.value.sort = res.sort;
      })
      .finally(() => {
        loading.value = false;
      });
    return;
  }

  // 编辑
  loading.value = true;
  View({ id: state.id })
    .then((res) => {
      res.content = res.content ? res.content.content : '';
      res.imagesList = [];
      if (res.images) {
        for (let i = 0; i < res.images.length; i++) {
          res.imagesList.push(res.images[i].image);
        }
      }

      formValue.value = res;
    })
    .finally(() => {
      loading.value = false;
    });
}

defineExpose({
  openModal,
});
</script>

<style lang="less"></style>